package com.example.init;

import com.example.util.ConfigUtil;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Slf4j
public class MinioUtil {
//    private static final Logger log = LoggerFactory.getLogger(MinioUtil.class);

    private final static String DEFAULT_BUCKET = "testbucket";
    private static MinioClient minioClient;

    static {
        try {
            MinioConfig minioConfig = ConfigUtil.getConfig("minio", MinioConfig.class);
            minioClient = MinioClient.builder()
                    .endpoint(minioConfig.getUrl()) // 替换为你的 MinIO 服务器地址
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey()) // 替换为你的 MinIO 访问密钥和密钥
                    .build();
            //创建bucket
            String bucketName = DEFAULT_BUCKET;
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("Bucket created: " + bucketName);
            } else {
                log.info("Bucket already exists: " + bucketName);
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    //https://www.explinks.com/blog/sq-ua-minio-api-documentation-quickstart/
    //文件上传下载的实现：https://developer.aliyun.com/article/1378940
    public static void uploadFile() {
        String filePath = "C:/Users/wzp/Desktop/hello.jpg";
        String objectName = "hello.jpg";
        File file = new File(filePath);
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(DEFAULT_BUCKET)
                    .object(objectName)
                    .stream(stream, file.length(), -1)
                    .build());
            System.out.println("File uploaded: " + objectName);
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if(null!=stream) {
                    stream.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static InputStream downFile() {
        try {
            GetObjectResponse object = minioClient.getObject(GetObjectArgs.builder().bucket(DEFAULT_BUCKET).object("hello.jpg").build());
            return object;
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
